#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基于LangChain Agent的云顶之弈智能助手
替换原有的硬编码查询路由逻辑，使用Agent自主决策
"""

import os
import sys
import asyncio
import json
import warnings
from typing import Optional, List, Dict, Any
from enum import Enum
from dataclasses import dataclass
from datetime import datetime

# 抑制警告
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)

# 导入Agent系统
from agent_system import agent_orchestrator
from agent_tools import get_available_tools, get_tool_by_name


class DataSource(Enum):
    """数据源枚举（保持兼容性）"""
    AGENT = "agent"  # 新增Agent模式
    LOCAL_RAG = "local_rag"
    OPGG_MCP = "opgg_mcp"
    WEB_SEARCH = "web_search"
    HYBRID = "hybrid"
    BASIC_SEARCH = "basic_search"


@dataclass
class QueryResult:
    """查询结果数据类"""
    content: str
    source: DataSource
    confidence: float
    metadata: Optional[Dict[str, Any]] = None
    agent_data: Optional[Dict[str, Any]] = None  # 新增Agent相关数据


class AgentTFTAssistant:
    """基于LangChain Agent的云顶之弈智能助手"""

    def __init__(self):
        self.agent_orchestrator = agent_orchestrator
        self.is_initialized = False
        self.conversation_history = []

    async def initialize(self):
        """初始化Agent系统"""
        print("初始化LangChain Agent智能助手...")
        print("=" * 50)

        # 尝试初始化Agent系统
        try:
            # 从环境变量获取API密钥
            openai_api_key = os.getenv("OPENAI_API_KEY")
            if not openai_api_key:
                # 检查配置文件
                config_file = "config.json"
                if os.path.exists(config_file):
                    with open(config_file, 'r', encoding='utf-8') as f:
                        config = json.load(f)
                        openai_api_key = config.get('openai_api_key')

            # 验证API密钥
            if not openai_api_key:
                raise Exception("未找到API密钥")

            # 获取模型配置
            model = "gpt-3.5-turbo"  # 默认模型
            if os.path.exists("config.json"):
                with open(config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    model = config.get('model', model)

            # 初始化Agent
            success = await self.agent_orchestrator.initialize(
                openai_api_key=openai_api_key,
                model=model
            )

            if success:
                self.is_initialized = True
                print("LangChain Agent系统初始化成功")
                self._show_agent_status()
            else:
                raise Exception("Agent系统初始化失败")

        except Exception as e:
            print(f"初始化失败: {e}")
            print("系统需要有效的OpenAI API密钥才能运行")
            raise Exception("无法启动Agent系统，请检查API密钥配置")

    async def _initialize_fallback(self):
        """初始化回退模式（使用原有逻辑）"""
        try:
            # 导入原有的组件
            from start import BasicTextSearch, OPGGMCPClient, HybridTFTAssistantWithFallback

            print("启用回退组件...")
            self.fallback_assistant = HybridTFTAssistantWithFallback()
            await self.fallback_assistant.initialize()
            print("回退模式启动成功")

        except Exception as e:
            print(f"回退模式初始化失败: {e}")

    def _show_agent_status(self):
        """显示Agent系统状态"""
        status = self.agent_orchestrator.get_status()
        print("Agent状态:")
        print(f"   模型: {status['model']}")
        print(f"   工具数量: {status['available_tools']}")
        print(f"   对话历史: {status['conversation_count']} 条")

    def show_system_menu(self):
        """显示系统菜单"""
        print("\n系统菜单")
        print("=" * 30)

        if not self.is_initialized:
            print("❌ Agent系统未初始化")
            return

        print("1. 开始对话")
        print("2. 系统状态")
        print("3. 对话历史")
        print("4. 帮助")
        print("5. 退出")

        while True:
            choice = input("\n请选择 (1-5): ").strip()

            if choice == "1":
                return True
            elif choice == "2":
                self.show_system_status()
                continue
            elif choice == "3":
                self.show_conversation_history()
                continue
            elif choice == "4":
                self.show_help()
                continue
            elif choice == "5":
                print("感谢使用，再见！")
                sys.exit(0)
            else:
                print("请输入有效选项")

    def show_system_status(self):
        """显示系统状态"""
        print("\n📊 系统状态详情")
        print("=" * 30)

        if self.is_initialized:
            status = self.agent_orchestrator.get_status()
            print(f"🤖 Agent系统: {'✅ 运行中' if status['initialized'] else '❌ 未初始化'}")
            print(f"🧠 AI模型: {status['model']}")
            print(f"🔧 可用工具: {status['available_tools']} 个")
            print(f"💬 对话数量: {status['conversation_count']} 条")

            print("\n🔧 可用工具列表:")
            for tool in get_available_tools():
                print(f"   • {tool['name']}: {tool['description'][:60]}...")

        else:
            print("❌ Agent系统未初始化")

        if self.fallback_mode:
            print("\n🔄 回退模式: ✅ 启用")
            print("   - 基础搜索功能")
            print("   - 模拟OPGG数据")
            print("   - 固定路由逻辑")

    def show_conversation_history(self):
        """显示对话历史"""
        print("\n💬 对话历史")
        print("=" * 30)

        if self.is_initialized:
            summary = self.agent_orchestrator.get_conversation_summary()
            print(summary)
        else:
            print("暂无对话记录")

        print(f"\n📈 总对话数: {len(self.conversation_history)}")

    def show_help(self):
        """显示帮助信息"""
        help_text = """
🎯 智能助手 - 帮助信息

## 🤖 Agent智能模式 (推荐)
• AI自主决策工具使用
• 智能搜索关键词优化
• 自然语言理解和回答生成
• 支持复杂查询和上下文对话
• 最佳用户体验

## 🔧 使用技巧
• **具体查询**: "小米汽车最新评价如何？" 而不是 "小米怎么样"
• **包含时间词**: "最新"、"最近"、"当前版本"
• **明确需求**: "推荐"、"对比"、"评价"、"新闻"

## 💬 查询示例
• "小米汽车最近发布了什么新产品？"
• "云顶之弈当前版本最强阵容推荐"
• "分析最新的AI技术发展趋势"
• "帮我比较一下特斯拉和比亚迪的优缺点"

## 🔄 回退模式
• 传统的菜单式操作
• 固定的工具选择
• 预定义的响应模板
• 稳定可靠的基础功能

## 🚀 开始使用
1. 选择 Agent 模式体验智能对话
2. 直接输入你的问题，让AI自主决策
3. 观察AI的思考过程和工具选择
4. 获得智能化的回答和建议
        """
        print(help_text)

    async def process_query(self, query: str) -> QueryResult:
        """处理用户查询"""
        print(f"\n正在处理查询: {query}")

        try:
            if not self.is_initialized:
                return QueryResult(
                    content="Agent系统未初始化，请检查配置。",
                    source=DataSource.AGENT,
                    confidence=0.1,
                    metadata={"error": "system_not_initialized"}
                )

            # 使用Agent处理
            return await self._agent_process_query(query)

        except Exception as e:
            print(f"查询处理失败: {e}")
            return QueryResult(
                content=f"处理您的查询时遇到问题: {str(e)}\n\n建议：\n1. 检查API密钥配置\n2. 确认网络连接正常\n3. 重新表述问题",
                source=DataSource.AGENT,
                confidence=0.1,
                metadata={"error": str(e)}
            )

    async def _agent_process_query(self, query: str) -> QueryResult:
        """使用Agent处理查询"""
        try:
            result = await self.agent_orchestrator.process_query(query)

            # 记录对话历史
            self.conversation_history.append({
                "query": query,
                "response": result.get("output", ""),
                "timestamp": datetime.now().isoformat(),
                "mode": "agent",
                "success": result.get("success", False),
                "tool_usage": result.get("tool_usage", 0)
            })

            # 显示Agent决策过程（如果有）
            if result.get("intermediate_steps"):
                print(f"🧠 Agent决策过程: 使用了 {result.get('tool_usage', 0)} 个工具")

            return QueryResult(
                content=result.get("output", ""),
                source=DataSource.AGENT,
                confidence=0.95 if result.get("success", False) else 0.3,
                metadata={
                    "mode": "agent",
                    "tool_usage": result.get("tool_usage", 0),
                    "intermediate_steps": result.get("intermediate_steps", []),
                    "agent_scratchpad": result.get("agent_scratchpad", "")
                },
                agent_data=result
            )

        except Exception as e:
            print(f"❌ Agent处理失败: {e}")
            return QueryResult(
                content=f"AI处理失败: {str(e)}\n\n💡 建议：\n1. 尝试简化问题\n2. 检查API密钥配置\n3. 使用回退模式",
                source=DataSource.AGENT,
                confidence=0.1,
                metadata={"error": str(e), "mode": "agent"}
            )

    async def _fallback_process_query(self, query: str) -> QueryResult:
        """使用回退模式处理查询"""
        try:
            # 使用原有的混合模式逻辑
            result = await self.fallback_assistant.process_query(query)

            # 转换为新的数据结构
            return QueryResult(
                content=result.content,
                source=DataSource.HYBRID,
                confidence=result.confidence,
                metadata={
                    "mode": "fallback",
                    "original_source": result.source.value
                }
            )

        except Exception as e:
            print(f"❌ 回退处理失败: {e}")
            return QueryResult(
                content=f"处理失败: {str(e)}",
                source=DataSource.HYBRID,
                confidence=0.1,
                metadata={"error": str(e), "mode": "fallback"}
            )

    async def interactive_chat(self):
        """交互式聊天"""
        print("\nLangChain Agent 智能助手")
        print("=" * 50)

        # 检查系统状态
        if not self.is_initialized:
            print("❌ Agent系统未初始化，请检查配置后重新启动")
            return

        self._show_agent_status()
        print("智能AI模式就绪")

        while True:
            # 显示菜单
            self.show_system_menu()

            # 获取用户查询
            query = input("\n请输入你的问题: ").strip()

            if not query:
                continue

            if query.lower() in ['/quit', '/exit', 'q', '退出']:
                print("感谢使用，再见！")
                break
            elif query.lower() in ['/help', '帮助']:
                self.show_help()
                continue
            elif query.lower() in ['/status', '状态']:
                self.show_system_status()
                continue
            elif query.lower() in ['/clear', '清空']:
                self.conversation_history.clear()
                self.agent_orchestrator.clear_history()
                print("对话历史已清空")
                continue

            # 处理查询
            print("正在思考...")
            result = await self.process_query(query)

            # 显示结果
            print(f"\n回答:")
            print(f"{result.content}")

            # 显示置信度和元数据
            confidence_text = "高" if result.confidence >= 0.8 else "中" if result.confidence >= 0.5 else "低"
            print(f"\n置信度: {confidence_text} ({result.confidence:.1f}/1.0)")

            # 显示额外信息
            if result.metadata:
                if result.metadata.get("tool_usage"):
                    print(f"使用工具数量: {result.metadata['tool_usage']}")
                if result.metadata.get("error"):
                    print(f"处理警告: {result.metadata['error']}")

            print("\n" + "-" * 50)

    async def run(self):
        """运行助手"""
        """主运行方法"""
        try:
            await self.initialize()
            await self.interactive_chat()
        except KeyboardInterrupt:
            print("\n👋 程序被用户中断")
        except Exception as e:
            print(f"❌ 程序运行出错: {e}")


async def main():
    """主函数"""
    try:
        assistant = AgentTFTAssistant()
        await assistant.run()
    except Exception as e:
        print(f"❌ 启动失败: {e}")


if __name__ == "__main__":
    asyncio.run(main())